<?php
/**
 * Manage mychoonz session
 */
class MczSession
{
  private $authenticated;
  private $login;
  private $name;
  private $lang;
  private $skin;
  private $lastfm_usr;
  private $lastfm_pass;
  private $token;
  private $tries;
  private $rights;
  private $home_dir;
  private $error;
  
  public function __construct()
  {
   $this->authenticated = FALSE;
	 $this->login         = '';
	 $this->name          = '';
	 $this->skin          = 'default';
	 $this->lastfm_usr  = '';
	 $this->lastfm_pass   = '';
	 $this->lang          = $this->browserLang();
	 $this->token         = uniqid('tok',TRUE);
	 $this->tries         = 0;
	 $this->rights        = array();
	 $this->home_dir      = '/dev/null';
	 $this->error         = '';
  }
  
  /**
   *Login method
   *
   *@param string $login
   *@param string $pass
   */
  public function logIn($login,$pass)
  {
    if($this->tries > 3)// prevent abuse
    {
      die();
    }
    else
    {
      $sql = "SELECT * FROM usr,grp WHERE usr.grp_id = grp.id AND usr.id='".sqlite_escape_string($login)."' AND usr.password='".sha1($pass)."' AND usr.status='active' LIMIT 1";
      $dbh = new dbSql();
      $res = $dbh->query($sql);
      if(!empty($res))
      {
        $this->error          = '';
        $this->authenticated  = TRUE;
        $this->login          = $res[0]['usr.id'];
        $this->name           = $res[0]['usr.name'];
        $this->skin           = $res[0]['usr.skin'];
        $this->lastfm_usr     = $res[0]['usr.lastfm_usr'];
        $this->lastfm_pass    = $res[0]['usr.lastfm_pass'];
        $this->home_dir       = HOME_PATH.$this->login;
        if(empty($res[0]['usr.lang']))
        {
          $this->switchLang($this->browserLang());// first-time connection
        }
        else
        {
          $this->lang = $res[0]['usr.lang'];
        }
        $this->rights = array();
        foreach($res[0] as $key=>$value)// set session rights
        {
          if(substr($key,0,6)=='grp.r_' and $value == 'T')
          {
            $this->rights[] = substr($key,6);
          }
        }
        $this->logConnection();
        if(!is_dir($this->home_dir))// create user dir if needed
        {
          mkdir($this->home_dir.'/local_import',0755,TRUE);
        }
      }
      else
      {
        $this->error = STR_ERR_AUTH;// set auth error message
        $this->tries++;// increase login tries counter
      }
    }
  }
  
  /**
   *Logs successful connections
   */
  private function logConnection()
  {
    $sql="INSERT INTO connection values('".$this->login."','".$_SERVER['REQUEST_TIME']."','".$_SERVER['REMOTE_ADDR']."')";
    $dbh = new dbSql();
    $dbh->exec($sql);
  }
  
  /**
   *Changes language according to a 2 letter code (en, es, fr...)
   *
   *@param string $lang
   */
  public function switchLang($lang)
  {
    if(is_file(APP_PATH.'app/lng/'.$lang.'.ini'))
    {
      $this->lang = $lang;
      $sql = "UPDATE usr SET lang='".sqlite_escape_string($this->lang)."' WHERE id='".$this->login."'";
      $dbh = new dbSql();
      $dbh->exec($sql);
    }
  }
  
  /**
   *Sets user password
   *
   *@param string $pwd
   */
  public function setMczPwd($pwd)
  {
    $sql = "UPDATE usr SET password='".sha1($pwd)."' WHERE id='".$this->login."'";
    $dbh = new dbSql();
    $dbh->exec($sql);
  }
  
  /**
   *Sets LastFm password. Given string must be a md5 hash
   *
   *@param string $pwd
   */
  public function setLastfmPwd($pwd)
  {
    $this->lastfm_pass = md5($pwd);
    $sql = "UPDATE usr SET lastfm_pass='".$this->lastfm_pass."' WHERE id='".$this->login."'";
    $dbh = new dbSql();
    $dbh->exec($sql);
  }
  
  /**
   *Sets LastFm user
   *
   *@param string $usr
   */
  public function setLastfmUsr($usr)
  {
    $this->lastfm_usr = $usr;
    $sql = "UPDATE usr SET lastfm_usr='".$this->lastfm_usr."' WHERE id='".$this->login."'";
    $dbh = new dbSql();
    $dbh->exec($sql);
  }
  
  /**
   * Change current skin. Checks if skin exists and also updates user prefs.
   * 
   * @param string $skin
   */     
  public function switchSkin($skin)
  {
    if(is_file(APP_PATH.'app/skin/'.$skin.'/screen.css'))
    {
      $this->skin = $skin;
      $sql = "UPDATE usr SET skin='".sqlite_escape_string($this->skin)."' WHERE id='".$this->login."'";
      $dbh = new dbSql();
      $dbh->exec($sql);
    }
  }
  /**
   * Get user prefered skin. Falls back to default if doesn't exist
   * 
   * @return string      
   */     
  public function getSkin()
  {
    if(is_file(APP_PATH.'app/skin/'.$this->skin.'/screen.css'))
    {
      return($this->skin);
    }
    else
    {
      return('default');
    }
  }
  /**
   * Return wether user is authenticated or not
   * 
   * @return boolean
   */           
  public function isAuth()
  {
    return($this->authenticated);
  }
  
  /**
   *Check user right to do something (play, download, delete_all, etc...)
   *
   *@param string $right
   *@return boolean
   */
  public function can($right)
  {
    if(in_array($right,$this->rights))
    {
      return(TRUE);
    }
    else
    {
      return(FALSE);
    }
  }
  
  /**
   *returns wether the user is admin or not
   *
   *@return boolean
   */
  public function isAdmin()
  {
    if(in_array('admin',$this->rights))
    {
      return(TRUE);
    }
    else
    {
      return(FALSE);
    }
  }
  /**
   * Generate a new session token
   */     
  public function changeToken()
  {
    $this->token = uniqid('tok',TRUE);
  }
  /**
   * get current session token
   *
   *@return string
   */
  public function getToken()
  {
    return((string)$this->token);
  }
  public function getHomeDir()
  {
    return((string)$this->home_dir);
  }
  /**
   * Calls constructor, inits session
   */     
  public function logOut()
  {
	 $this->__construct(); 
  }
  /**
   * Returns the session's 2 letter country code
   * 
   * @return string   
   */     
  public function lang()
  {
    return($this->lang);
  }
  public function getLogin()
  {
    return($this->login);
  }
  
  /**
   *return lastfm user name
   *
   *@return string
   */
  public function getLastfmUsr()
  {
    return($this->lastfm_usr);
  }
  /**
   *return lastfm password md5 hash
   *
   *@return string
   */
  public function getLastfmPass()
  {
    return($this->lastfm_pass);
  }
  /**
   * Tries to determine a 2 letter code from browser's accepted language.
   * 
   * Defaults to 'en'
   *
   * @return string $lang   
   */              
  private function browserLang()
  {
    if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
    {
      $lang = explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
      $lang = strtolower(substr(chop($lang[0]),0,2));
      if(empty($lang))
      {
        return('en');
      }
      return $lang;
    }
    else
    {
      return('en');
    }
  }
  public function lastError()
  {
    return($this->error);
  }
  
  /**
   *returns html for preferences form
   *
   *@return string
   */
  public function mkPrefForm()
  {
    $skins = glob(APP_PATH.'app/skin/*',GLOB_ONLYDIR);
    foreach($skins as $skin)
    {
      $skin_values[basename($skin)] = basename($skin);
    }
    $skin_select = Html::mkSelect(array('script'=>'onchange="switchSkin(this.value);"','values'=>$skin_values,'class'=>'prefTab','selected'=>$this->skin));

    $langs = glob(APP_PATH.'app/lng/*.ini');
    foreach($langs as $lang)
    {
      $lang_values[basename($lang,'.ini')] = basename($lang,'.ini');
    }
    $lang_select = Html::mkSelect(array('script'=>'onchange="switchLang(this.value);"','values'=>$lang_values,'class'=>'prefTab','selected'=>$this->lang));

    if(empty($this->lastfm_usr))
    {
      $lastfm_url = 'http://www.last.fm';
    }
    else
    {
      $lastfm_url = 'http://www.last.fm/user/'.$this->lastfm_usr;
    }
    
    $access_rights = '<ul class="rights">';
    if($this->can('admin'))
    {
      $access_rights.='<li>'.STR_UI_CAN_ADMIN.'</li>';
    }
    if($this->can('play'))
    {
      $access_rights.='<li>'.STR_UI_CAN_PLAY.'</li>';
    }
    if($this->can('download'))
    {
      $access_rights.='<li>'.STR_UI_CAN_DOWNLOAD.'</li>';
    }
    if($this->can('add_file'))
    {
      $access_rights.='<li>'.STR_UI_CAN_ADD_FILE.'</li>';
    }
    if($this->can('dist'))
    {
      $access_rights.='<li>'.STR_UI_CAN_DIST.'</li>';
    }
    if($this->can('mod_all'))
    {
      $access_rights.='<li>'.STR_UI_CAN_MOD_ALL.'</li>';
    }
    elseif($this->can('mod_own'))
    {
      $access_rights.='<li>'.STR_UI_CAN_MOD_OWN.'</li>';
    }
    if($this->can('del_all'))
    {
      $access_rights.='<li>'.STR_UI_CAN_DEL_ALL.'</li>';
    }
    elseif($this->can('del_own'))
    {
      $access_rights.='<li>'.STR_UI_CAN_DEL_OWN.'</li>';
    }
    $access_rights.= '</ul>';

    $html =  '<fieldset>
              <legend>'.STR_UI_DISCONNECT.'</legend>
              <a href="?c=logoff" onclick="return confirm(str.ui_logoff_confirm);">'.STR_UI_DISCONNECT_LINK.'</a>
              </fieldset>
              <form method="post" action="#" onsubmit="return false">
                <fieldset>
                  <legend>'.STR_UI_SETTINGS.'</legend>
                  '.$lang_select.'&nbsp;<label>'.STR_UI_LANG.'</label><br/>
                  '.$skin_select.'&nbsp;<label>'.STR_UI_SKIN.'</label><br/>
                </fieldset>
              </form>
               <form method="post" action="#" onsubmit="updateUserIds();return false;">
                <fieldset>
                  <legend>'.STR_UI_YOUR_IDS.'</legend>
                  <input type="text" disabled="disabled" value="'.$this->login.'"/>&nbsp;<label>'.STR_UI_MYCHOONZ_ID.'</label>&nbsp;<input type="image" src="app/skin/transparent.gif" class="btnPassword" onmouseover="help(str.hlp_user_change_password);" onclick="setPrefMczPass();return false;"/><br/>
                  <input id="prefLastfmId" type="text" onmouseover="help(str.hlp_enter_id);" value="'.$this->lastfm_usr.'"/>&nbsp;<label><a href="'.$lastfm_url.'" target="_blank">'.STR_UI_LASTFM_ID.'</a></label>&nbsp;<input type="image" src="app/skin/transparent.gif" class="btnPassword" onmouseover="help(str.hlp_user_change_password);" onclick="setPrefLastfmPass();return false;"/><br/>
                  <input id="prefLastfmPass" type="hidden" />
                  <input type="hidden" id="prefMczPass"/>
                  <input type="submit" value="'.STR_UI_OK.'"/>
                </fieldset>
             </form>
              <fieldset>
                <legend>'.STR_UI_YOUR_RIGHTS.'</legend>
                '.STR_UI_YOU_CAN.$access_rights.'
              </fieldset>
              ';
    return $html;
  }
  
}
?>
